<script setup lang="ts">
defineOptions({
  name: "addBottleInfo"
});
import { ref, reactive, computed, onMounted } from "vue";
import type { FormInstance, FormRules } from "px-ui";
import { createGasBottleInfo, updateGasBottleInfo, queryGasBottleInfoDetail } from "@/api/modules/operation";
import { queryFileList } from "@/api/modules/fab";
import { queryEquipSystem } from "@/api/equip/archive";
import { useThrottleFn } from "@vueuse/core";
import { throttleDelay as delay } from "@/utils/constant";
import FileUpload from "@/components/Upload/FileUpload.vue";

interface Props {
  // 弹框类型 add 新增   edit 编辑
  type: "add" | "edit";
  id: string;
}

const props = withDefaults(defineProps<Props>(), {});

const dialogTableVisible = defineModel({ type: Boolean, default: false });

const loading = ref<boolean>(false);
const title = computed(() => (props.type === "add" ? "新增" : "编辑"));
const gasNameOptions = ref<Array<any>>([]);
//  图片上传类型add：新增，edit：编辑，view：查看
const uploadType = ref<string>("add");
const fileList = ref<Array<any>>([]);
const isDeleteLocal = ref<boolean>(false);

interface RuleForm {
  materialNo: string;
  gasName: string;
  description: string;
}
const ruleFormRef = ref<FormInstance>();
const ruleForm = reactive<RuleForm>({
  materialNo: "",
  gasName: "",
  description: ""
});

const rules = reactive<FormRules<RuleForm>>({
  materialNo: [{ required: true, message: "请输入料号", trigger: "blur" }],
  gasName: [{ required: true, message: "请输入气体名称", trigger: "blur" }],
  description: [{ required: false, message: "请输入备注", trigger: "blur" }]
});

const emits = defineEmits(["submit"]);

const cancelHandler = () => {
  dialogTableVisible.value = false;
};

const changeFileListHandler = (fl: Array<any>) => {
  fileList.value = [];
  if (!fl?.length) return;
  fileList.value = fl.map(item => item);
};

const submitHandler = useThrottleFn(async () => {
  if (!ruleFormRef.value) return;
  await ruleFormRef.value.validate(async (valid, fields) => {
    if (valid) {
      loading.value = true;
      const fileIds = fileList.value?.map(item => item.id);
      const fileNameList = fileList.value?.map(item => item.originalName);
      const { id } = props;
      const params = { ...ruleForm, fileIds, fileNameList };
      if (props.type === "add") {
        await createGasBottleInfo(params, () => {
          loading.value = false;
        });
      } else if (props.type === "edit") {
        params["id"] = id;
        await updateGasBottleInfo(params, () => {
          loading.value = false;
        });
      }
      loading.value = false;
      emits("submit");
      dialogTableVisible.value = false;
    } else {
      console.error("error submit!", fields);
    }
  });
}, delay);

const initOptions = async () => {
  gasNameOptions.value = [];
  const res: Array<any> = await queryEquipSystem({ className: "GAS" });
  // facCode   一期  FAC_83abf9   二期  FAC_93abf6
  const facCode = localStorage.getItem("facCode");
  const systemCode = facCode === "FAC_83abf9" ? "SCA6CC96" : facCode === "FAC_93abf6" ? "SCC3F1B9" : "";
  const t = res.find(item => item.code === systemCode);
  if (!t?.children?.length) return;
  gasNameOptions.value = t.children.map(item => {
    let { name } = item;
    const reg = new RegExp("供应系统", "g");
    name = name.replace(reg, "");
    return { label: name, value: name };
  });
};

const queryFileListFn = async (ids: Array<string>) => {
  if (!ids?.length) return;
  const params = { ids };
  const res = await queryFileList(params, () => {
    loading.value = false;
  });
  loading.value = false;
  if (!res?.length) return;
  fileList.value = res;
};

const init = async () => {
  await initOptions();
  if (props.type === "edit") {
    uploadType.value = "edit";
    isDeleteLocal.value = true;
    const { id } = props;
    loading.value = true;
    const res = await queryGasBottleInfoDetail(id, () => {
      loading.value = false;
    });
    const { materialNo = "", gasName = "", description = "", fileIds = [] } = res;
    ruleForm.materialNo = materialNo;
    ruleForm.gasName = gasName;
    ruleForm.description = description;
    await queryFileListFn(fileIds);
    loading.value = false;
  }
};

onMounted(async () => {
  await init();
});
</script>

<template>
  <px-dialog v-model="dialogTableVisible" :title="title" width="1000px">
    <px-form ref="ruleFormRef" v-loading="loading" :model="ruleForm" :rules="rules" inline label-width="100px" class="demo-ruleForm" status-icon>
      <px-row :gutter="32">
        <px-col :span="24">
          <px-form-item label="料号" prop="materialNo">
            <px-input v-model.trim="ruleForm.materialNo" clearable placeholder="请输入料号" />
          </px-form-item>
        </px-col>
        <px-col :span="24">
          <px-form-item label="气体名称" prop="gasName">
            <px-select v-model="ruleForm.gasName" clearable filterable placeholder="请选择气体名称">
              <px-option v-for="item in gasNameOptions" :key="item.value" :label="item.label" :value="item.value" />
            </px-select>
          </px-form-item>
        </px-col>
        <px-col :span="24">
          <px-form-item label="备注" prop="description">
            <px-input v-model.trim="ruleForm.description" clearable type="textarea" maxlength="200" show-word-limit placeholder="请输入备注" />
          </px-form-item>
        </px-col>
        <px-col :span="24">
          <px-form-item label="上传文档" prop="fileIdList" class="item-upload">
            <FileUpload
              :multiple="false"
              :isDeleteLocal="isDeleteLocal"
              :fileType="uploadType"
              :fileList="fileList"
              :countLimit="1"
              @changeFileList="changeFileListHandler"
            />
          </px-form-item>
        </px-col>
      </px-row>
    </px-form>
    <template #footer>
      <span class="dialog-footer">
        <px-button @click="cancelHandler">取消</px-button>
        <px-button type="primary" :loading="loading" @click="submitHandler"> 确认 </px-button>
      </span>
    </template>
  </px-dialog>
</template>

<style lang="scss" scoped>
:deep(.px-form-item) {
  width: 100%;

  .item-upload {
    .px-form-item__content {
      margin-left: 0 !important;
    }
  }

  .px-form-item__content {
    .px-input,
    .px-select,
    .px-date-picker,
    .px-time-picker,
    .px-tree-select {
      width: 100%;
    }
  }
}
</style>
